package com.cedarhd.brzx.domain.repository.specification;

import com.cedarhd.brzx.domain.entity.Student;
import com.cedarhd.brzx.dto.request.StudentQueryDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;

/**
 * @author Evan
 * @date 2018/3/6
 */
public class StudentSpecification {
    public static Specification<Student> buildFromDTO(StudentQueryDTO dto) {
        return (root, query, builder) -> {

            ArrayList<Predicate> list = new ArrayList<>();

            if (StringUtils.isNotBlank(dto.getStudtntName())) {
                list.add(builder.like(root.get("studentName"), "%" + dto.getStudtntName() + "%"));
            }

            if (dto.getAge() != null) {
                list.add(builder.equal(root.get("age"), dto.getAge()));
            }

            if (dto.getEffective() != null) {
                list.add(builder.equal(root.get("effective"), dto.getEffective()));
            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }

}
